import { defineStore } from 'pinia'
import request from '../utils/request.js'

// 定义用户 store
const useUserStore = defineStore('user', {
  state: () => ({
    // 当前登录用户的用户名
    username: '',
    // JWT 令牌
    token: '',
    // 用户ID
    userId: '',
    // 用户是否已登录
    isLoggedIn: false
  }),
  
  getters: {
    // 获取当前登录状态
    getLoginStatus: (state) => state.isLoggedIn,
    // 获取用户名
    getUsername: (state) => state.username,
    // 获取令牌
    getToken: (state) => state.token
  },
  
  actions: {
    // 用户登录
    async login(username, password) {
      try {
        const response = await request.post('/user/login', null, {
          params: {
            username,
            password
          }
        })
        
        if (response.code === 0) {
          // 登录成功，保存用户信息
          this.username = username
          this.token = response.data
          this.isLoggedIn = true
          
          // 持久化保存到 localStorage
          this.saveToLocalStorage()
          
          return { success: true, data: response.data }
        } else {
          // 登录失败
          return { success: false, message: response.msg }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: '登录失败，请重试' }
      }
    },
    
    // 用户注册
    async register(username, password) {
      try {
        const response = await request.post('/user/register', null, {
          params: {
            username,
            password
          }
        })
        
        if (response.code === 0) {
          return { success: true, message: response.msg }
        } else {
          return { success: false, message: response.msg }
        }
      } catch (error) {
        console.error('注册失败:', error)
        return { success: false, message: '注册失败，请重试' }
      }
    },
    
    // 退出登录
    logout() {
      this.username = ''
      this.token = ''
      this.userId = ''
      this.isLoggedIn = false
      
      // 清除 localStorage
      this.clearLocalStorage()
    },
    
    // 持久化保存到 localStorage
    saveToLocalStorage() {
      localStorage.setItem('userInfo', JSON.stringify({
        username: this.username,
        token: this.token,
        userId: this.userId,
        isLoggedIn: this.isLoggedIn
      }))
    },
    
    // 从 localStorage 加载
    loadFromLocalStorage() {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          this.username = userInfo.username || ''
          this.token = userInfo.token || ''
          this.userId = userInfo.userId || ''
          this.isLoggedIn = userInfo.isLoggedIn || false
        } catch (error) {
          console.error('加载用户信息失败:', error)
        }
      }
    },
    
    // 清除 localStorage
    clearLocalStorage() {
      localStorage.removeItem('userInfo')
    }
  }
})

export default useUserStore